import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import transformers
from transformers.activations import gelu
from transformers.modeling_outputs import (
    BaseModelOutputWithPoolingAndCrossAttentions,
    SequenceClassifierOutput,
)
from transformers.models.bert.modeling_bert import (
    BertLMPredictionHead,
    BertModel,
    BertPreTrainedModel,
)
from transformers.models.roberta.modeling_roberta import (
    RobertaLMHead,
    RobertaModel,
    RobertaPreTrainedModel,
)


class MLPLayer(nn.Module):
    """
    Head for getting sentence representations over RoBERTa/BERT's CLS representation.
    """

    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.activation = nn.Tanh()

    def forward(self, features, **kwargs):
        x = self.dense(features)
        x = self.activation(x)

        return x


class EntityMLPLayer(nn.Module):
    """
    Head for getting entity representations.
    """

    def __init__(
        self, config, entity_dim, use_non_linear_transformation, activation="tanh"
    ):
        super().__init__()
        self.dense = nn.Linear(entity_dim, config.hidden_size)
        self.dense2 = nn.Linear(config.hidden_size, config.hidden_size)
        self.use_non_linear_transformation = use_non_linear_transformation

        if activation == "relu":
            self.activation = nn.ReLU()
        else:
            self.activation = nn.Tanh()

    def forward(self, features, **kwargs):
        x = self.dense(features)
        x = self.activation(x)
        if self.use_non_linear_transformation:
            x = self.dense2(x)

        return x


class Similarity(nn.Module):
    """
    Dot product or cosine similarity
    """

    def __init__(self, temp):
        super().__init__()
        self.temp = temp
        self.cos = nn.CosineSimilarity(dim=-1)

    def forward(self, x, y):
        return self.cos(x, y) / self.temp


class Pooler(nn.Module):
    """
    Parameter-free poolers to get the sentence embedding
    'cls': [CLS] representation with BERT/RoBERTa's MLP pooler.
    'cls_before_pooler': [CLS] representation without the original MLP pooler.
    'avg': average of the last layers' hidden states at each token.
    'avg_top2': average of the last two layers.
    'avg_first_last': average of the first and the last layers.
    """

    def __init__(self, pooler_type):
        super().__init__()
        self.pooler_type = pooler_type
        assert self.pooler_type in [
            "cls",
            "cls_before_pooler",
            "avg",
            "avg_top2",
            "avg_first_last",
        ], (
            "unrecognized pooling type %s" % self.pooler_type
        )

    def forward(self, attention_mask, outputs):
        last_hidden = outputs.last_hidden_state
        pooler_output = outputs.pooler_output
        hidden_states = outputs.hidden_states

        if self.pooler_type in ["cls_before_pooler", "cls"]:
            return last_hidden[:, 0]
        elif self.pooler_type == "avg":
            return (last_hidden * attention_mask.unsqueeze(-1)).sum(
                1
            ) / attention_mask.sum(-1).unsqueeze(-1)
        elif self.pooler_type == "avg_first_last":
            first_hidden = hidden_states[0]
            last_hidden = hidden_states[-1]
            pooled_result = (
                (first_hidden + last_hidden) / 2.0 * attention_mask.unsqueeze(-1)
            ).sum(1) / attention_mask.sum(-1).unsqueeze(-1)
            return pooled_result
        elif self.pooler_type == "avg_top2":
            second_last_hidden = hidden_states[-2]
            last_hidden = hidden_states[-1]
            pooled_result = (
                (last_hidden + second_last_hidden) / 2.0 * attention_mask.unsqueeze(-1)
            ).sum(1) / attention_mask.sum(-1).unsqueeze(-1)
            return pooled_result
        else:
            raise NotImplementedError


def cl_init(cls, config):
    """
    Contrastive learning class init function.
    """
    cls.pooler_type = cls.model_args.pooler_type
    cls.pooler = Pooler(cls.model_args.pooler_type)
    cls.mlp = MLPLayer(config)
    cls.simcse_sim = Similarity(temp=cls.model_args.simcse_temp)
    cls.ease_sim = Similarity(temp=cls.model_args.ease_temp)
    cls.entity_transformation = EntityMLPLayer(
        config,
        cls.model_args.entity_emb_dim,
        cls.model_args.use_non_linear_transformation,
        cls.model_args.activation,
    )

    if cls.model_args.use_another_transformation_for_hn:
        cls.hn_entity_transformation = MLPLayer(config)
    else:
        cls.hn_entity_transformation = cls.entity_transformation

    cls.entity_embedding = nn.Embedding(
        cls.model_args.entity_emb_shape[0], cls.model_args.entity_emb_shape[1]
    )
    cls.entity_embedding.weight.requires_grad = True

    cls.init_weights()


def cl_forward(
    cls,
    encoder,
    input_ids=None,
    attention_mask=None,
    token_type_ids=None,
    position_ids=None,
    head_mask=None,
    inputs_embeds=None,
    labels=None,
    output_attentions=None,
    output_hidden_states=None,
    return_dict=None,
    mlm_input_ids=None,
    mlm_labels=None,
    title_id=None,
    hn_title_ids=None,
    # hn_title_id=None
):
    
    """
    The main difference between ours and SimCSE's original implementation is that
    we also use our novel entity contrastive learning loss between sentences and their related entities.
    """
    return_dict = return_dict if return_dict is not None else cls.config.use_return_dict
    ori_input_ids = input_ids
    batch_size = input_ids.size(0)
    # Number of sentences in one instance
    # 2: pair instance; 3: pair instance with a hard negative
    num_sent = input_ids.size(1)

    mlm_outputs = None
    # Flatten input for encoding
    input_ids = input_ids.view((-1, input_ids.size(-1)))  # (bs * num_sent, len)
    attention_mask = attention_mask.view(
        (-1, attention_mask.size(-1))
    )  # (bs * num_sent len)
    if token_type_ids is not None:
        token_type_ids = token_type_ids.view(
            (-1, token_type_ids.size(-1))
        )  # (bs * num_sent, len)

    # Get raw embeddings
    outputs = encoder(
        input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=True
        if cls.model_args.pooler_type in ["avg_top2", "avg_first_last"]
        else False,
        return_dict=True,
    )

    # MLM auxiliary objective
    if mlm_input_ids is not None:
        mlm_input_ids = mlm_input_ids.view((-1, mlm_input_ids.size(-1)))
        mlm_outputs = encoder(
            mlm_input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=True
            if cls.model_args.pooler_type in ["avg_top2", "avg_first_last"]
            else False,
            return_dict=True,
        )

    # Pooling
    pooler_output = cls.pooler(attention_mask, outputs)
    pooler_output = pooler_output.view(
        (batch_size, num_sent, pooler_output.size(-1))
    )  # (bs, num_sent, hidden)

    # If using "cls", we add an extra MLP layer
    # (same as BERT's original implementation) over the representation.
    if cls.pooler_type == "cls" or cls.model_args.use_mlp_forcibly:
        pooler_output = cls.mlp(pooler_output)

    # Separate representation
    z1, z2 = pooler_output[:, 0], pooler_output[:, 1]

    # Hard negative
    if num_sent == 3:
        z3 = pooler_output[:, 2]

    # Gather all embeddings if using distributed training
    if dist.is_initialized() and cls.training:
        # Gather hard negative
        if num_sent >= 3:
            z3_list = [torch.zeros_like(z3) for _ in range(dist.get_world_size())]
            dist.all_gather(tensor_list=z3_list, tensor=z3.contiguous())
            z3_list[dist.get_rank()] = z3
            z3 = torch.cat(z3_list, 0)

        # Dummy vectors for allgather
        z1_list = [torch.zeros_like(z1) for _ in range(dist.get_world_size())]
        z2_list = [torch.zeros_like(z2) for _ in range(dist.get_world_size())]
        # Allgather
        dist.all_gather(tensor_list=z1_list, tensor=z1.contiguous())
        dist.all_gather(tensor_list=z2_list, tensor=z2.contiguous())

        # Since allgather results do not have gradients, we replace the
        # current process's corresponding embeddings with original tensors
        z1_list[dist.get_rank()] = z1
        z2_list[dist.get_rank()] = z2
        # Get full batch embeddings: (bs x N, hidden)
        z1 = torch.cat(z1_list, 0)
        z2 = torch.cat(z2_list, 0)

    # entity embedding
    entity_embedding = cls.entity_embedding(title_id)

    if cls.model_args.use_entity_transformation:
        entity_embedding = cls.entity_transformation(entity_embedding)

    # ea cossim
    ease_cos_sim = cls.ease_sim(z1.unsqueeze(1), entity_embedding.transpose(0, 1))

    if cls.model_args.use_equal_loss:
        ease_cos_sim2 = cls.ease_sim(z2.unsqueeze(1), entity_embedding.transpose(0, 1))

    # hard negativeのweight
    z3_weight = cls.model_args.hard_negative_weight

    # ea hard negative
    if cls.model_args.hard_negative_num > 0:

        # TODO ここはまとめて計算する
        for hn_title_id in hn_title_ids.T:
            hn_entity_embedding = cls.entity_embedding(hn_title_id.unsqueeze(1))
            if cls.model_args.use_entity_transformation:
                hn_entity_embedding = cls.entity_transformation(hn_entity_embedding)

            # ea hn cossim
            ease_hn_cos_sim = cls.ease_sim(
                z1.unsqueeze(1), hn_entity_embedding.transpose(0, 1)
            )

            # weightを作成
            weights = torch.eye(ease_hn_cos_sim.size(0)).to(cls.device) * z3_weight

            # weightを足す
            ease_hn_cos_sim = ease_hn_cos_sim + weights

            # 今までのcos_simに追加する
            ease_cos_sim = torch.cat([ease_cos_sim, ease_hn_cos_sim], 1)

    cos_sim = cls.simcse_sim(z1.unsqueeze(1), z2.unsqueeze(0))

    # Hard negative
    if num_sent >= 3:
        z1_z3_cos = cls.sim(z1.unsqueeze(1), z3.unsqueeze(0))
        cos_sim = torch.cat([cos_sim, z1_z3_cos], 1)

    # labels: 0, 1?
    labels = torch.arange(cos_sim.size(0)).long().to(cls.device)
    loss_fct = nn.CrossEntropyLoss()

    # Calculate loss with hard negatives
    if num_sent == 3:
        # Note that weights are actually logits of weights
        z3_weight = cls.model_args.hard_negative_weight
        weights = torch.tensor(
            [
                [0.0] * (cos_sim.size(-1) - z1_z3_cos.size(-1))
                + [0.0] * i
                + [z3_weight]
                + [0.0] * (z1_z3_cos.size(-1) - i - 1)
                for i in range(z1_z3_cos.size(-1))
            ]
        ).to(cls.device)
        cos_sim = cos_sim + weights

    simcse_loss = loss_fct(cos_sim, labels)

    # entity contrastive learning loss
    ease_labels = torch.arange(ease_cos_sim.size(0)).long().to(cls.device)
    ease_loss = loss_fct(ease_cos_sim, ease_labels)

    if cls.model_args.use_equal_loss:
        ease_labels2 = torch.arange(ease_cos_sim2.size(0)).long().to(cls.device)
        ease_loss2 = loss_fct(ease_cos_sim2, ease_labels2)
        ease_loss = 0.5 * ease_loss + 0.5 * ease_loss2

    if cls.model_args.use_entity_to_sentence_loss:
        ease_cos_sim2 = cls.ease_sim(entity_embedding, z1.unsqueeze(0))
        ease_labels2 = torch.arange(ease_cos_sim2.size(0)).long().to(cls.device)
        ease_loss2 = loss_fct(ease_cos_sim2, ease_labels2)
        ease_loss = ease_loss + ease_loss2

    # Calculate loss for EASE
    loss = (
        cls.model_args.simcse_loss_ratio * simcse_loss
        + cls.model_args.ease_loss_ratio * ease_loss
    )

    # Calculate loss for MLM
    masked_lm_loss = None
    if mlm_outputs is not None and mlm_labels is not None:
        mlm_labels = mlm_labels.view(-1, mlm_labels.size(-1))
        prediction_scores = cls.lm_head(mlm_outputs.last_hidden_state)
        masked_lm_loss = loss_fct(
            prediction_scores.view(-1, cls.config.vocab_size), mlm_labels.view(-1)
        )
        loss = loss + cls.model_args.mlm_loss_ratio * masked_lm_loss

    if not return_dict:
        output = (cos_sim,) + outputs[2:]
        return ((loss,) + output) if loss is not None else output

    sequence_classifier_output = SequenceClassifierOutput(
        loss=loss,
        logits=cos_sim,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
    )
    sequence_classifier_output.simcse_loss = (
        cls.model_args.simcse_loss_ratio * simcse_loss
    )
    sequence_classifier_output.ease_loss = cls.model_args.ease_loss_ratio * ease_loss
    sequence_classifier_output.mlm_loss = None
    if masked_lm_loss is not None:
        sequence_classifier_output.mlm_loss = (
            cls.model_args.mlm_loss_ratio * masked_lm_loss
        )
    return sequence_classifier_output


## Sentence embedding出力用
def sentemb_forward(
    cls,
    encoder,
    input_ids=None,
    attention_mask=None,
    token_type_ids=None,
    position_ids=None,
    head_mask=None,
    inputs_embeds=None,
    labels=None,
    output_attentions=None,
    output_hidden_states=None,
    return_dict=None,
):

    return_dict = return_dict if return_dict is not None else cls.config.use_return_dict

    outputs = encoder(
        input_ids,
        attention_mask=attention_mask,
        token_type_ids=token_type_ids,
        position_ids=position_ids,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        output_attentions=output_attentions,
        output_hidden_states=True
        if cls.pooler_type in ["avg_top2", "avg_first_last"]
        else False,
        return_dict=True,
    )

    pooler_output = cls.pooler(attention_mask, outputs)
    if (
        cls.pooler_type == "cls" and not cls.model_args.mlp_only_train
    ) or cls.model_args.use_mlp_forcibly:
        pooler_output = cls.mlp(pooler_output)

    if not return_dict:
        return (outputs[0], pooler_output) + outputs[2:]

    return BaseModelOutputWithPoolingAndCrossAttentions(
        pooler_output=pooler_output,
        last_hidden_state=outputs.last_hidden_state,
        hidden_states=outputs.hidden_states,
    )


class BertForEACL(BertPreTrainedModel):
    _keys_to_ignore_on_load_missing = [r"position_ids"]

    def __init__(self, config, *model_args, **model_kargs):
        super().__init__(config)
        self.model_args = model_kargs["model_args"]
        self.bert = BertModel(config)
        self.lm_head = BertLMPredictionHead(config)
        cl_init(self, config)

    def init_entity_embedding(self, entity_embeddings):
        self.entity_embedding.weight = nn.Parameter(
            torch.FloatTensor(entity_embeddings)
        )
        self.entity_embedding.weight.requires_grad = True

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,
        output_attentions=None,
        output_hidden_states=None,
        return_dict=None,
        sent_emb=False,
        mlm_input_ids=None,
        mlm_labels=None,
        title_id=None,
        hn_title_ids=None,
    ):
        if sent_emb:
            return sentemb_forward(
                self,
                self.bert,
                input_ids=input_ids,
                attention_mask=attention_mask,
                token_type_ids=token_type_ids,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                labels=labels,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
            )
        else:
            return cl_forward(
                self,
                self.bert,
                input_ids=input_ids,
                attention_mask=attention_mask,
                token_type_ids=token_type_ids,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                labels=labels,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                mlm_input_ids=mlm_input_ids,
                mlm_labels=mlm_labels,
                title_id=title_id,
                hn_title_ids=hn_title_ids,
            )


class RobertaForEACL(RobertaPreTrainedModel):
    _keys_to_ignore_on_load_missing = [r"position_ids"]

    def __init__(self, config, *model_args, **model_kargs):
        super().__init__(config)
        self.model_args = model_kargs["model_args"]
        self.roberta = RobertaModel(config)
        self.lm_head = RobertaLMHead(config)
        cl_init(self, config)

    def init_entity_embedding(self, entity_embeddings):
        self.entity_embedding.weight = nn.Parameter(
            torch.FloatTensor(entity_embeddings)
        )
        self.entity_embedding.weight.requires_grad = True

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,
        output_attentions=None,
        output_hidden_states=None,
        return_dict=None,
        sent_emb=False,
        mlm_input_ids=None,
        mlm_labels=None,
        title_id=None,
        hn_title_ids=None,
    ):
        if sent_emb:
            return sentemb_forward(
                self,
                self.roberta,
                input_ids=input_ids,
                attention_mask=attention_mask,
                token_type_ids=token_type_ids,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                labels=labels,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
            )
        else:
            return cl_forward(
                self,
                self.roberta,
                input_ids=input_ids,
                attention_mask=attention_mask,
                token_type_ids=token_type_ids,
                position_ids=position_ids,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                labels=labels,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
                mlm_input_ids=mlm_input_ids,
                mlm_labels=mlm_labels,
                title_id=title_id,
                hn_title_ids=hn_title_ids,
            )
